package com.dy.utils;



import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;


import cn.hutool.core.lang.UUID;



/**
 * 
 * <pre>项目名称：bootstrap_demo    
 * 类名称：OssUtils    
 * 类描述：    
 * 创建人：baijh
 * 创建时间：2022年3月18日 上午9:23:16    
 * 修改人：baijh
 * 修改时间：2022年3月18日 上午9:23:16    
 * 修改备注：       
 * @version </pre>
 */
public class Oss_chengdu_blog {
	
    //终端，访问的服务地址
	private static final String endpoint = "oss-cn-chengdu.aliyuncs.com";
    //oss的访问密钥id
    private static final String accessKeyId = "LTAI5tP2h5JqKfVggbRRHeV5";
    //对应的密钥，身份验证信息
    private static final String accessKeySecret = "Z7IOKS7FxoQf3s2x2HSXLYimRZIqOF";
    //需要操作的bucket '桶'名称
    private static final String bucketName = "chengdu-dycyd";
    //文件夹名
    private static final String file = "Blog-Img/";


    /**
     * @Author dy
     * @Description: 上传文件到 OSS
     */
    public static String uploadFile(MultipartFile img){

    		InputStream input = null;
			try {
				String fileName = img.getOriginalFilename();
				input = img.getInputStream();

	            //建立一个oss连接
	            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
	            //截取文件名。替换成uuid
	            String fileFix = fileName.substring(fileName.lastIndexOf("."));
	            fileName = getUUId()+fileFix; //截取后 ： .png
	            fileName = file + fileName;
				ossClient.putObject(bucketName, fileName, input);
				ossClient.shutdown();
				return fileName;
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(input != null){
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return null;
    }
    private static String getUUId(){
        return UUID.randomUUID().toString(true);
    }

    public static void deleteFile(String imageName){
		OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		client.deleteObject(bucketName, imageName);
		client.shutdown();
	}


	public static void deleteFile(List<String> imageName){
		OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		for (String s : imageName) {
			client.deleteObject(bucketName, s);
		}
		client.shutdown();
	}
}